<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Data Tab</title>
    <style>
        body {
            font-family: Arial, sans-serif;
            background-color: white;
            margin: 0;
            padding: 0;
        }
        .container {
            display: flex;
            flex-direction: column;
            padding: 10px;
        }
        .data-content {
            display: flex;
            padding: 10px;
            background-color: white;
        }
        .controls-box {
            display: flex;
            flex-direction: column;
            gap: 10px;
            padding: 10px;
        }
        table {
            border-collapse: collapse;
            width: 100%;
        }
        table, th, td {
            border: 1px solid black;
        }
        th, td {
            padding: 8px;
            text-align: left;
        }
        .drawing-grid {
            display: grid;
            grid-gap: 20px;
            padding: 10px;
            background-color: white;
            overflow: auto;
        }
        .drawing-pane {
            border: 1px solid black;
            background-color: white;
        }
    </style>
</head>
<body>
<div class="container">
    <div class="data-content">
        <table id="vectorTable">
            <thead>
            <tr>
                <th>Сечение</th>
                <th>ОП1</th>
                <th>ОП2</th>
                <th>ОП3</th>
            </tr>
            </thead>
            <tbody>
            <!-- Строки данных будут добавлены здесь -->
            </tbody>
        </table>
        <div class="controls-box">
            <label for="azimuth">Азимут:</label>
            <input type="text" id="azimuth" value="0">
            <label>
                <input type="radio" name="direction" value="counterClockwise" checked> Против часовой
            </label>
            <label>
                <input type="radio" name="direction" value="clockwise"> По часовой
            </label>
            <button id="calculateButton">Рассчитать</button>
            <button id="pasteButton">Вставить из буфера</button>
            <button id="addButton">Добавить строку</button>
            <button id="deleteButton">Удалить строку</button>
            <button id="loadButton">Загрузить Excel</button>
        </div>
    </div>
    <div id="drawingGrid" class="drawing-grid"></div>
</div>

<script>
    const MAX_RESULTANT_LENGTH = 66;

    class DataTabController {
        constructor(resultTabController) {
            this.table = document.getElementById('vectorTable').querySelector('tbody');
            this.azimuth = document.getElementById('azimuth');
            this.clockwiseButton = document.querySelector('input[name="direction"][value="clockwise"]');
            this.resultTabController = resultTabController;
            this.initListeners();
        }

        initListeners() {
            document.getElementById('calculateButton').addEventListener('click', () => this.drawResultantVectors());
            document.getElementById('pasteButton').addEventListener('click', () => this.pasteFromClipboard());
            document.getElementById('addButton').addEventListener('click', () => this.addRow());
            document.getElementById('deleteButton').addEventListener('click', () => this.deleteRow());
            document.getElementById('loadButton').addEventListener('click', () => this.loadFromExcel());
        }

        addRow() {
            const row = this.table.insertRow();
            row.insertCell().innerHTML = `<input type="text">`;
            row.insertCell().innerHTML = `<input type="text">`;
            row.insertCell().innerHTML = `<input type="text">`;
            row.insertCell().innerHTML = `<input type="text">`;
        }

        deleteRow() {
            const selectedRow = this.table.querySelector('tr.selected');
            if (selectedRow) {
                this.table.deleteRow(selectedRow.rowIndex - 1);
            }
        }

        pasteFromClipboard() {
            // Имитация вставки данных из буфера обмена
            const dataFromClipboard = [
                { name: '30', length1: '10', length2: '20', length3: '-30' },
                { name: '40', length1: '15', length2: '25', length3: '-35' }
            ];
            dataFromClipboard.forEach(data => {
                const row = this.table.insertRow();
                row.insertCell().innerHTML = `<input type="text" value="${data.name}">`;
                row.insertCell().innerHTML = `<input type="text" value="${data.length1}">`;
                row.insertCell().innerHTML = `<input type="text" value="${data.length2}">`;
                row.insertCell().innerHTML = `<input type="text" value="${data.length3}">`;
            });
        }

        loadFromExcel() {
            // Имитация загрузки данных из Excel
            const dataFromFile = [
                { name: '50', length1: '20', length2: '30', length3: '-40' },
                { name: '60', length1: '25', length2: '35', length3: '-45' }
            ];
            this.table.innerHTML = '';
            dataFromFile.forEach(data => {
                const row = this.table.insertRow();
                row.insertCell().innerHTML = `<input type="text" value="${data.name}">`;
                row.insertCell().innerHTML = `<input type="text" value="${data.length1}">`;
                row.insertCell().innerHTML = `<input type="text" value="${data.length2}">`;
                row.insertCell().innerHTML = `<input type="text" value="${data.length3}">`;
            });
        }

        drawResultantVectors() {
            this.resultTabController.clearDrawingGridPane();

            const isClockwise = this.clockwiseButton.checked;
            const azimuthValue = parseFloat(this.azimuth.value) || 0;

            const vectorDataList = Array.from(this.table.rows).map(row => ({
                name: row.cells[0].querySelector('input').value,
                length1: parseFloat(row.cells[1].querySelector('input').value) || 0,
                length2: parseFloat(row.cells[2].querySelector('input').value) || 0,
                length3: parseFloat(row.cells[3].querySelector('input').value) || 0,
            }));

            let column = 0;
            let row = 0;
            const maxColumns = 3;

            vectorDataList.forEach(data => {
                try {
                    const vectorLengths = [data.length1, data.length2, data.length3];
                    const vectors = VectorCalculator.calculateVectors(vectorLengths, isClockwise);

                    const resultVector = VectorCalculator.calculateResultantVector(vectors);
                    const resultLength = Math.sqrt(resultVector[0] * resultVector[0] + resultVector[1] * resultVector[1]);

                    const scale = this.calculateScale(resultLength);

                    const drawingPane = document.createElementNS("http://www.w3.org/2000/svg", "svg");
                    drawingPane.setAttribute("width", "300");
                    drawingPane.setAttribute("height", "250");
                    drawingPane.classList.add('drawing-pane');

                    VectorDrawer.drawTriangleAndVector(drawingPane, 100, 100, 150, resultVector, data.name, resultLength, azimuthValue, scale, isClockwise);

                    this.resultTabController.addDrawingPane(drawingPane, column, row);

                    column++;
                    if (column === maxColumns) {
                        column = 0;
                        row++;
                    }

                } catch (e) {
                    console.error("Please enter valid numbers for vector lengths and scale.");
                }
            });
        }

        calculateScale(resultLength) {
            return MAX_RESULTANT_LENGTH / resultLength;
        }
    }

    class ResultTabController {
        constructor() {
            this.drawingGrid = document.getElementById('drawingGrid');
        }

        clearDrawingGridPane() {
            this.drawingGrid.innerHTML = '';
        }

        addDrawingPane(drawingPane, column, row) {
            drawingPane.classList.add('drawing-pane');
            this.drawingGrid.appendChild(drawingPane);
        }
    }

    class VectorCalculator {
        static calculateVectors(vectorLengths, isClockwise) {
            // Реализация вычислений векторов на основе длин
            return vectorLengths.map(length => [length, length]); // Пример
        }

        static calculateResultantVector(vectors) {
            // Реализация вычислений результирующего вектора
            return vectors.reduce((acc, vec) => [acc[0] + vec[0], acc[1] + vec[1]], [0, 0]); // Пример
        }
    }

    class VectorDrawer {
        static drawTriangleAndVector(svg, x, y, size, vector, name, resultLength, azimuth, scale, isClockwise) {
            // Реализация рисования треугольника и вектора на SVG
            // Пример рисования: добавление линий и текста на SVG
        }
    }

    const resultTabController = new ResultTabController();
    const dataTabController = new DataTabController(resultTabController);

    // Добавление начальных данных
    dataTabController.addRow();
    dataTabController.addRow();
    document.querySelector('tbody tr:nth-child(1) input:nth-child(1)').value = '10';
    document.querySelector('tbody tr:nth-child(1) input:nth-child(2)').value = '10';
    document.querySelector('tbody tr:nth-child(1) input:nth-child(3)').value = '20';
    document.querySelector('tbody tr:nth-child(1) input:nth-child(4)').value = '-30';

    document.querySelector('tbody tr:nth-child(2) input:nth-child(1)').value = '20';
    document.querySelector('tbody tr:nth-child(2) input:nth-child(2)').value = '10';
    document.querySelector('tbody tr:nth-child(2) input:nth-child(3)').value = '-20';
    document.querySelector('tbody tr:nth-child(2) input:nth-child(4)').value = '30';
</script>
</body>
</html>
